package com.z.system.security;

import com.z.system.model.User;
import com.z.system.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 自定义UserDetailsService实现，用于从数据库加载用户信息
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(CustomUserDetailsService.class);

    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 根据用户名加载用户信息
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库中查找用户
        User user = userRepository.findByUserSn(username)
                .orElseThrow(() -> new UsernameNotFoundException("User not found with username: " + username));
        
        // 使用原生SQL查询用户的权限信息
        Set<GrantedAuthority> authorities = getAuthoritiesByUserId(user.getId());
        
        // 设置用户权限
        user.setAuthorities(authorities);
        
        logger.debug("Loaded user: {} with {} authorities", username, authorities.size());
        
        // 返回用户对象（User类已实现UserDetails接口）
        return user;
    }
    
    /**
     * 使用原生SQL通过用户ID查询权限列表
     */
    private Set<GrantedAuthority> getAuthoritiesByUserId(java.util.UUID userId) {
        Set<GrantedAuthority> authorities = new HashSet<>();
        
        try {
            // 原生SQL查询：通过用户ID获取所有权限
            String sql = """
                SELECT DISTINCT p.permission 
                FROM t_permission p 
                JOIN t_role_permission rp ON p.id = rp.permission_id 
                JOIN t_dept_user_role ur ON rp.role_id = ur.role_id 
                WHERE ur.user_id = ?
            """;
            
            List<String> permissionStrings = jdbcTemplate.queryForList(sql, String.class, userId);
            
            // 转换为GrantedAuthority对象
            for (String permission : permissionStrings) {
                authorities.add(new SimpleGrantedAuthority(permission));
            }
            
        } catch (Exception e) {
            logger.error("Failed to load authorities for user with id: {}", userId, e);
        }
        
        return authorities;
    }
}